package code.starivan.leetcode;

/**
 * Created by Ivan on 2015/8/22.
 */

//Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
public class N003_LongestSubstring {
    public int lengthOfLongestSubstring(String s) {
        if(s==null||s.isEmpty())
            return 0;
        char[] arr=s.toCharArray();
        int length=arr.length;
        int[] visit=new int[256];
        for(int i=0;i<255;i++)
            visit[i]=-1;

        int maxLnegth=0;
        int currentLength=0;
        int indexStart=0;

        for(int i=0;i<length;i++){
            char c=arr[i];
            if(visit[c]==-1){
                currentLength++;
                visit[c]=i;
            }else{
                int oldIndex=visit[c];
                if(oldIndex<indexStart){
                    currentLength++;

                }else{
                    currentLength=i-oldIndex;
                    indexStart=oldIndex+1;

                }

                visit[c]=i;
            }


            if(currentLength>maxLnegth){
                maxLnegth=currentLength;
                indexStart=i+1-maxLnegth;
            }
        }

        return maxLnegth;
    }
}
